package idv.arthur.jenkins;

import idv.arthur.widgets.Widgets;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jvnet.hudson.client_demo.URLConnectionUtil;

public class SpecificJobStatus {
	static Widgets wid = new Widgets();
	final static String modId = "3C";
	final static int jobNumber = 3;
	//static String urlStr = wid.JENKINSURL+modId+"/"+jobNumber+"/api/xml";
	static String urlStr = "http://10.144.97.99:8330/jenkins/job/1A/13/api/json";
	
	static Map<String,Object> map = new HashMap<String,Object>();
	
	public static void main(String[] args) throws InterruptedException {
		
        try {
        	System.out.println(getJobStatus());
        } catch (FileNotFoundException e) {
        	System.out.println("並未執行過此Job");
        } catch (Exception e) {
        	e.printStackTrace();
        }
	}
	
	private static String getJobStatus() throws Exception {
		
		String status = "還沒開始";
		
		InputStream ins = URLConnectionUtil.doGet(urlStr,false,wid.JENKINS_USR,wid.JENKINS_PWD,map);
		final SAXReader reader = new SAXReader();
		Document document = reader.read(ins);
		Element root = document.getRootElement();
		Iterator<Element> it = root.elementIterator();
		boolean isDoing = true;
    	while (it.hasNext()) {
			Element e = it.next();
			if ( "action".equalsIgnoreCase(e.getName() ) ) {
				status = "執行中";
			}
		}
		it = root.elementIterator();	
    	while (it.hasNext()) {
			Element e = it.next();
			if ( "result".equalsIgnoreCase(e.getName() ) ) {
				status = e.getText();
			}
		}
    	ins.close();
		return status;
	}

}
